package com.example.cemenghuii.service;

import com.example.cemenghuii.entity.News;
import com.example.cemenghuii.mapper.NewsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewsService {

    @Autowired
    private NewsMapper newsMapper;

    /**
     * 根据ID查询新闻
     */
    public News getNewsById(Long id) {
        return newsMapper.selectById(id);
    }

    /**
     * 创建新闻
     */
    public boolean createNews(News news) {
        news.setCreateTime(LocalDateTime.now());
        news.setUpdateTime(LocalDateTime.now());
        news.setViewCount(0);

        // 企业用户发布的新闻需要审核
        if (news.getPublisherId() != null) {
            news.setStatus(0); // 待审核
        } else {
            news.setStatus(1); // 管理员发布直接通过
            news.setPublishTime(LocalDateTime.now());
        }

        return newsMapper.insert(news) > 0;
    }

    /**
     * 更新新闻
     */
    public boolean updateNews(News news) {
        news.setUpdateTime(LocalDateTime.now());
        return newsMapper.update(news) > 0;
    }

    /**
     * 删除新闻
     */
    public boolean deleteNews(Long id) {
        return newsMapper.deleteById(id) > 0;
    }

    /**
     * 分页查询新闻列表
     */
    public Map<String, Object> getNewsList(String title, String author, Integer status,
                                           Long publisherId, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<News> newsList = newsMapper.selectNewsList(title, author, status, publisherId, offset, pageSize);
        int total = newsMapper.countNews(title, author, status, publisherId);

        Map<String, Object> result = new HashMap<>();
        result.put("list", newsList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 审核新闻
     */
    public boolean auditNews(Long id, Integer status) {
        News news = newsMapper.selectById(id);
        if (news == null) {
            throw new RuntimeException("新闻不存在");
        }

        if (status == 1) {
            // 审核通过，设置发布时间
            news.setPublishTime(LocalDateTime.now());
            news.setStatus(status);
            news.setUpdateTime(LocalDateTime.now());
            return newsMapper.update(news) > 0;
        } else {
            // 审核不通过
            return newsMapper.updateStatus(id, status) > 0;
        }
    }

    /**
     * 增加浏览量
     */
    public boolean incrementViewCount(Long id) {
        return newsMapper.incrementViewCount(id) > 0;
    }

    /**
     * 获取待审核新闻列表
     */
    public Map<String, Object> getPendingNewsList(Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<News> newsList = newsMapper.selectPendingNews(offset, pageSize);
        int total = newsMapper.countPendingNews();

        Map<String, Object> result = new HashMap<>();
        result.put("list", newsList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 小程序端获取已发布新闻列表
     */
    public Map<String, Object> getPublishedNewsList(String keyword, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<News> newsList = newsMapper.selectPublishedNews(keyword, offset, pageSize);
        int total = newsMapper.countPublishedNews(keyword);

        Map<String, Object> result = new HashMap<>();
        result.put("list", newsList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 根据用户ID查询新闻列表
     */
    public Map<String, Object> getNewsByPublisherId(Long publisherId, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<News> newsList = newsMapper.selectByPublisherId(publisherId, offset, pageSize);
        int total = newsMapper.countByPublisherId(publisherId);

        Map<String, Object> result = new HashMap<>();
        result.put("list", newsList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 获取新闻详情（包含浏览量增加）
     */
    public News getNewsDetail(Long id, boolean incrementView) {
        News news = newsMapper.selectById(id);
        if (news != null && incrementView) {
            newsMapper.incrementViewCount(id);
            news.setViewCount(news.getViewCount() + 1);
        }
        return news;
    }

    /**
     * 检查用户是否有权限操作该新闻
     */
    public boolean checkNewsPermission(Long newsId, Long userId, Integer userType) {
        // 超级管理员可以操作所有新闻
        if (userType == 2) {
            return true;
        }

        // 企业用户只能操作自己的新闻
        News news = newsMapper.selectById(newsId);
        return news != null && news.getPublisherId().equals(userId);
    }
}